﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MIMSWeb.Models;
using MIMSWeb.Infrastructure.Abstract;
using MIMSCore.Abstract;
using MIMSCore.Logging;

namespace MIMSWeb.Controllers
{
    public class AccountController : Controller
    {
        IAuthProvider authProvider;
        ILogger<SynkronLogger> _logger;

        public AccountController(IAuthProvider provider, ILogger<SynkronLogger> logger)
        {
            authProvider = provider;
            _logger = logger;
        }

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    
                    if (authProvider.Authenticate(model.Username, model.Password))
                    {
                        return Redirect(returnUrl ?? Url.Action("Index", "Home"));
                    }
                    else
                    {
                        ModelState.AddModelError("", "Invalid Username or Password");
                    }
                }
                catch(Exception Ex)
                {
                    
                    //Log Exception
                    _logger.WriteCritical(2000, string.Format("Message: {0} | Stack Trace: {1}", Ex.Message, Ex.StackTrace),
                        new Dictionary<string, object> { { "User Credentials", model } });
                }
            }
            return View();
        }

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(string username, string password)
        {
            System.Web.Security.Membership.CreateUser(username, password);

            return View();
        }

        public ActionResult CreateUser()
        {
            return View();
        }

        public ActionResult LogOff()
        {
            authProvider.LogOff();

            return RedirectToAction("Login", "Account");
        }
    }
}
